package com.example.demo.future;

import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: xxx
 * @time: 2020-12-12 12:32
 * @author: baojinlong
 **/
public class JDKThreadPoolSubmitTest {
    /**
     * 有三种 submit。这三种按照提交任务的类型来算分为两个类型。
     * 提交执行 Callable 类型的任务。
     */
    public static void main(String[] args) throws Exception {

    }

    /**
     * 一种 execute，无返回值。三种 submit，有返回值 三种 submit 方法里面调用的都是 execute 方法
     *
     * @throws InterruptedException
     * @throws java.util.concurrent.ExecutionException
     */
    private static void method03() throws InterruptedException, java.util.concurrent.ExecutionException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
        AtomicInteger atomicInteger = new AtomicInteger();
        Future<AtomicInteger> future = executor.submit(() -> {
            System.out.println("关注why技术");
            //在这里进行计算逻辑
            atomicInteger.set(5201314);
        }, atomicInteger);

        System.out.println("future的内容:" + future.get());
        Thread.currentThread().join();
    }

    /**
     * future.get() 方法的返回值为 null
     *
     * @throws InterruptedException
     * @throws java.util.concurrent.ExecutionException
     */
    private static void method02() throws InterruptedException, java.util.concurrent.ExecutionException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
        Future<?> future = executor.submit(() -> {
            System.out.println("关注why技术");
        });
        //  future.get() 方法的返回值为 null
        System.out.println("future的内容:" + future.get());
        Thread.currentThread().join();
    }

    /**
     * 提交执行 Callable 类型的任务*
     *
     * @throws InterruptedException
     * @throws java.util.concurrent.ExecutionException
     */
    private static void method01() throws InterruptedException, java.util.concurrent.ExecutionException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
        Future<String> future = executor.submit(() -> {
            System.out.println("关注why技术");
            return "这次一定！";
        });
        System.out.println("future的内容:" + future.get());
        Thread.currentThread().join();
    }


}
